package top.btcmarket.auth.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
//import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import top.btcmarket.auth.entity.User;
import top.btcmarket.auth.service.UserService;

@Controller
public class HelloWorldRestController {
  
    @Autowired
    UserService userService;  //Service which will do all data retrieval/manipulation work
  
      
    //-------------------Retrieve All Users--------------------------------------------------------
    // use leo
    // Spring Security默认的角色前缀是”ROLE_”,使用hasRole方法时已经默认加上了，因此我们在数据库里面的用户角色应该是“ROLE_user”，在user前面加上”ROLE_”前缀
    // 因此 leo 需要有一个 角色的名称 为  ROLE_admin , 才能访问该接口
    
//    @PreAuthorize("hasRole('admin')")
    @RequestMapping(value = "/user/", method = RequestMethod.GET)
    @ResponseBody
    public List<User> listAllUsers() {
        List<User> users = userService.findAll();
        if(users.isEmpty()){
            return null;
        }
        return users;
    }
    
    //use aden  只需要token 就可以访问
    
    @RequestMapping(value = "/userNoRole/", method = RequestMethod.GET)
    @ResponseBody
    public List<User> listAllUsersNoRole() {
        List<User> users = userService.findAll();
        if(users.isEmpty()){
            return null;
        }
        return users;
    }
    
    
    @RequestMapping(value = "/userPath/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<User> testUrlPath(HttpServletRequest request,@PathVariable("id") String id) {
    	
    	 /*String pattern = (String)
    		        request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);  
    	 
    	 String method = request.getMethod();
    	 
    	 
    	 System.out.println("controller,pattern+---------"+pattern+",method:"+method);*/
    	 

    	 /*System.out.println("Fetching User with id " + id);
    	 
    	 
    	 Enumeration<String> attributeNames = request.getAttributeNames();
			while (attributeNames.hasMoreElements()) {
				System.out.println(" ---testUrlPath--attributeNames------"+attributeNames.nextElement());
			}
    	*/
    /*	 String path = (String) request.getAttribute(
		            HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
		    String bestMatchPattern = (String ) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
		    System.out.println(",path,"+path+",bestMatchPattern,"+bestMatchPattern);
		    AntPathMatcher apm = new AntPathMatcher();
		    String finalPath = apm.extractPathWithinPattern(bestMatchPattern, path);
		    System.out.println(""+finalPath);
    	 
		    String urlTail = new AntPathMatcher()
		            .extractPathWithinPattern( bestMatchPattern, request.getRequestURI() );
		    
		    System.out.println(urlTail);*/
		    
    	 
         User user = userService.findById(Integer.parseInt(id));
         if (user == null) {
             System.out.println("User with id " + id + " not found");
             return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
         }
         return new ResponseEntity<User>(user, HttpStatus.OK);
    }
    
    
  
  
  
    //-------------------Retrieve Single User--------------------------------------------------------
    // 查询指定的用户， 通过 url 来控制 
    
    
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_XML_VALUE})
    public ResponseEntity<User> getUser(@PathVariable("id") String id) {
        System.out.println("Fetching User with id " + id);
        User user = userService.findById(Integer.parseInt(id));
        if (user == null) {
            System.out.println("User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }
  
      
      
    //-------------------Create a User--------------------------------------------------------
      
    /*@RequestMapping(value = "/user/", method = RequestMethod.POST)
    public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder) {
        System.out.println("Creating User " + user.getName());
  
        if (userService.isUserExist(user)) {
            System.out.println("A User with name " + user.getName() + " already exist");
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
        }
  
        userService.saveUser(user);
  
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }*/
  
      
    //------------------- Update a User --------------------------------------------------------
      
    /*@RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
    public ResponseEntity<User> updateUser(@PathVariable("id") long id, @RequestBody User user) {
        System.out.println("Updating User " + id);
          
        User currentUser = userService.findById(id);
          
        if (currentUser==null) {
            System.out.println("User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
  
        currentUser.setName(user.getName());
        currentUser.setAge(user.getAge());
        currentUser.setSalary(user.getSalary());
          
        userService.updateUser(currentUser);
        return new ResponseEntity<User>(currentUser, HttpStatus.OK);
    }*/
  
    //------------------- Delete a User --------------------------------------------------------
      
    /*@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<User> deleteUser(@PathVariable("id") long id) {
        System.out.println("Fetching & Deleting User with id " + id);
  
        User user = userService.findById(id);
        if (user == null) {
            System.out.println("Unable to delete. User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
  
        userService.deleteUserById(id);
        return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
    }*/
  
      
    //------------------- Delete All Users --------------------------------------------------------
      
    /*@RequestMapping(value = "/user/", method = RequestMethod.DELETE)
    public ResponseEntity<User> deleteAllUsers() {
        System.out.println("Deleting All Users");
  
        userService.deleteAllUsers();
        return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
    }*/
  
}